package utilities;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedWriter;
import java.io.FileWriter;

public class FileManagement {

	public void save(String fnimi, String sisend){
		try{
			FileWriter kirjutaja = new FileWriter(fnimi, false);
			BufferedWriter out = new BufferedWriter(kirjutaja);
			out.write((sisend));
			out.close();
		}catch(Exception e){
			System.err.println("Error: " + e.getMessage());
		}
	}

	public String[][] read(String fName){
		String[][] out;
		int n = 0;
		out = new String[this.getFileLength(fName)][2];
		try{
			FileInputStream fstream = new FileInputStream(fName);
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String rida;
			
			while ((rida = br.readLine()) != null){
				String[] user = rida.split(":"); 
				out[n][0] = user[0];
				out[n][1] = user[1];
				n++;
			}
		}catch (Exception e){
			System.err.println("Error: " + e.getMessage());
		}
		return out;
	}
	
	public int getFileLength(String fName){
		int x = 0;
		try{
			FileInputStream fstream = new FileInputStream(fName);
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			while (br.readLine() != null){
				x++;
			}
		}catch (Exception e){
			System.err.println("Error: " + e.getMessage());
		}
		return x;
	}
}
